package com.springboot.nacos.config;

import com.small.nacos.api.NacosFactory;
import com.small.nacos.api.config.ConfigService;
import com.small.nacos.api.exception.NacosException;
import com.springboot.nacos.config.exception.runtime.NacosConnectionFailureException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

public class NacosConfigManager {

    private final static Logger LOGGER = LoggerFactory.getLogger(NacosConfigManager.class);

    private NacosConfigProperties nacosConfigProperties;

    private static ConfigService service = null;

    public NacosConfigManager(NacosConfigProperties nacosConfigProperties) {
        this.nacosConfigProperties = nacosConfigProperties;
        createConfigService(nacosConfigProperties);
    }

    public ConfigService createConfigService(NacosConfigProperties nacosConfigProperties) {
        if (service == null) {
            synchronized (NacosConfigManager.class) {
                try {
                    if (service == null) {
                        service = NacosFactory.createConfigService(nacosConfigProperties.assembleConfigServiceProperties());
                    }
                } catch (NacosException e) {
                    LOGGER.error(e.getMessage());
                    throw new NacosConnectionFailureException(
                            nacosConfigProperties.getServerAddr(), e.getMessage(), e);
                }

            }
        }
        return service;
    }

    public ConfigService getConfigService() {
        if (Objects.isNull(service)) {
            createConfigService(this.nacosConfigProperties);
        }
        return service;
    }


    public NacosConfigProperties getNacosConfigProperties() {
        return nacosConfigProperties;
    }
}
